package com.jiuyin.dianjing.ui.fragment.match;

import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.bumptech.glide.Glide;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.viewholder.BaseViewHolder;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.jiuyin.dianjing.R;
import com.jiuyin.dianjing.api.constant.ApiConstant;
import com.jiuyin.dianjing.api.enums.ApiEnum;
import com.jiuyin.dianjing.api.interfaces.ApiResultCallback;
import com.jiuyin.dianjing.api.interfaces.ProgressDialogCallback;
import com.jiuyin.dianjing.api.server.ServerApi;
import com.jiuyin.dianjing.app.HelperApplication;
import com.jiuyin.dianjing.event.RefreshEvent;
import com.jiuyin.dianjing.model.CompeteDetail;
import com.jiuyin.dianjing.ui.activity.match.MatchApplyListActivity;
import com.jiuyin.dianjing.ui.activity.match.MatchEnterActivity;
import com.jiuyin.dianjing.ui.activity.match.MatchMyActivity;
import com.jiuyin.dianjing.ui.fragment.base.BaseLazyFragment;
import com.jiuyin.dianjing.util.DisplayUtil;
import com.jiuyin.dianjing.util.LogUtil;
import com.jiuyin.dianjing.util.PMUtil;
import com.jiuyin.dianjing.util.ToastUtil;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONObject;

import java.util.HashMap;

import butterknife.BindView;
import butterknife.OnClick;

import static com.jiuyin.dianjing.api.constant.ApiConstant.KEY_COMPETITIONID;
import static com.jiuyin.dianjing.api.constant.ApiConstant.KEY_TACTICS;
import static com.jiuyin.dianjing.api.constant.ApiConstant.KEY_TOKEN;

/**
 * 征召信息
 */
public class FragmentMatchRecruitmentInformation extends BaseLazyFragment {
    private static final String KEY = "KEY";
    @BindView(R.id.img_match_status)
    ImageView mMatchStatus;
    @BindView(R.id.tv_match_time_registration_begin)
    TextView mRegistrationBegan;
    @BindView(R.id.tv_match_time_registration_end)
    TextView mRegistrationEnd;
    @BindView(R.id.tv_match_time_match_begin)
    TextView mMatchBegan;
    @BindView(R.id.tv_match_time_match_end)
    TextView mMatchEnd;
    @BindView(R.id.tv_event_name_value)
    TextView mEventName;
    @BindView(R.id.tv_match_type_value)
    TextView mMatchType;
    @BindView(R.id.tv_match_create_competition_site_value)
    TextView mMatchSite;
    @BindView(R.id.tv_match_create_sponsor_value)
    TextView mSponsor;
    @BindView(R.id.tv_match_create_event_notification_group_value)
    TextView mEventNotification;
    @BindView(R.id.tv_match_create_principal_value)
    TextView mPrincipal;
    @BindView(R.id.tv_match_create_sponsor_introduction_value)
    TextView mSponsorIntroduction;
    @BindView(R.id.tv_match_competitor_value)
    TextView mParticipants;
    @BindView(R.id.tv_match_competitor_key)
    TextView mMatchCompetitor;
    @BindView(R.id.lv_match_competitor)
    RecyclerView mCompetitor;
    @BindView(R.id.tv_match_tournament_bonus_value)
    TextView mTournamentBonus;
    @BindView(R.id.tv_match_competition_rules_value)
    TextView mCompetitionRules;
    @BindView(R.id.tv_sign_up)
    Button btSubmit;

    private int mTactics;
    private String mCompetitionId;
    private BaseQuickAdapter<String, BaseViewHolder> mAdapter;
    /**
     * 参加比赛个数
     */
    private int mJoinNum = 0;

    public static FragmentMatchRecruitmentInformation newInstance(String competitionId) {
        Bundle bundle = new Bundle();
        bundle.putString(KEY, competitionId);
        FragmentMatchRecruitmentInformation fragmentGame = new FragmentMatchRecruitmentInformation();
        fragmentGame.setArguments(bundle);
        return fragmentGame;
    }

    @Override
    public void fetchData() {
        mCompetitionId = getArguments().getString(KEY);
        HashMap hashMap = new HashMap();
        hashMap.put(KEY_TOKEN, HelperApplication.getToken());
        hashMap.put(KEY_COMPETITIONID, mCompetitionId);
        JSONObject data = new JSONObject(hashMap);
        ApiResultCallback request = new ApiResultCallback() {
            @Override
            public void onSuccess(JsonObject data) {
                CompeteDetail compete = new Gson().fromJson(data, CompeteDetail.class);
                LogUtil.log("CompeteDetail = " + compete.toString());
                mMatchStatus.setImageLevel(compete.course.competeCourse);
                mRegistrationBegan.setText(compete.course.courseTime.get(0));
                mRegistrationEnd.setText(compete.course.courseTime.get(1));
                mMatchBegan.setText(compete.course.courseTime.get(2));
                mMatchEnd.setText(compete.course.courseTime.get(3));
                switch (compete.course.competeCourse) {
                    case 0:
                        btSubmit.setText(R.string.match_registration_not_started);
                        break;
                    case 1:
                        mRegistrationBegan.setTextColor(getResources().getColor(R.color.colorRed));
                        if (compete.status == 0){
                            btSubmit.setText(R.string.match_application_in_progress);
                        }else if (compete.status == 1){
                            btSubmit.setText(R.string.match_registration_success);
                        }else if (compete.status == 2){
                            btSubmit.setText(R.string.match_registration_refused);
                        }else if (compete.status == 3){
                            btSubmit.setText(R.string.match_registration_sign_up);
                            btSubmit.setOnClickListener(v -> {
                                submit();
                            });
                        }
                        break;
                    case 2:
                        mRegistrationBegan.setTextColor(getResources().getColor(R.color.colorRed));
                        mRegistrationEnd.setTextColor(getResources().getColor(R.color.colorRed));
                        btSubmit.setText(R.string.match_registration_end);
                        break;
                    case 3:
                        mRegistrationBegan.setTextColor(getResources().getColor(R.color.colorRed));
                        mRegistrationEnd.setTextColor(getResources().getColor(R.color.colorRed));
                        mMatchBegan.setTextColor(getResources().getColor(R.color.colorRed));
                        btSubmit.setText(R.string.match_registration_game_begun);
                        break;
                    case 4:
                        mRegistrationBegan.setTextColor(getResources().getColor(R.color.colorRed));
                        mRegistrationEnd.setTextColor(getResources().getColor(R.color.colorRed));
                        mMatchBegan.setTextColor(getResources().getColor(R.color.colorRed));
                        mMatchEnd.setTextColor(getResources().getColor(R.color.colorRed));
                        btSubmit.setText(R.string.match_match_end);
                        break;
                }
                //region 赛事信息
                mTactics = compete.tactics;
                mEventName.setText(compete.competition.name);
                mMatchType.setText(mTactics == 0 ? R.string.match_create_individual_competitive : R.string.match_create_team_sports);
                mMatchSite.setText(compete.competition.address);
                mMatchCompetitor.setText(mTactics == 0 ? R.string.match_competitor : R.string.match_competitor_team);
                //region 主办方资料
                mSponsor.setText(compete.competition.sponsor);
                mEventNotification.setText(compete.competition.flock);
                mPrincipal.setText(compete.competition.sponsor_name);
                mSponsorIntroduction.setText(compete.competition.intro);
                //region 其他
                mJoinNum = compete.headerList.size();
                mParticipants.setText(compete.headerList.size() + "/" + compete.competition.join_num);
                mAdapter.setNewInstance(compete.headerList);
                mTournamentBonus.setText(compete.competition.bonus_rule);
                mCompetitionRules.setText(compete.competition.game_rule);
            }

            @Override
            public void onFail(String msg) {
                ToastUtil.showShort(msg);
            }

            @Override
            public void onError(String msg) {
                LogUtil.log(msg);
            }
        };
        ProgressDialogCallback defaultProgressDialogCallback = new ProgressDialogCallback() {
            @Override
            public void showProgressDialog() {
                showLoading();
            }

            @Override
            public void dismissProgressDialog() {
                dismissLoading();
            }
        };
        ServerApi.post(ApiEnum.APP_COMPETE_DETAIL_API.getUrl(), data, null, defaultProgressDialogCallback, d -> addDisposable(d), request);
    }

    @Override
    protected int setLayoutId() {
        return R.layout.fragment_match_detail_recruitment_information;
    }

    @Override
    protected void initData() {
        mAdapter = new BaseQuickAdapter<String, BaseViewHolder>(R.layout.item_head) {
            @Override
            protected void convert(@NonNull BaseViewHolder holder, String str) {
                ImageView imageView = holder.getView(R.id.iv_head);
                Glide.with(getContext())
                        .load(str)
                        .placeholder(R.mipmap.bga_pp_ic_holder_dark)
                        .override(DisplayUtil.dp2px(getContext(), getResources().getDimension(R.dimen.dp_40)))
                        .into(imageView);
            }
        };
        mAdapter.setOnItemClickListener((adapter, view, position) -> {
            Bundle bundle = new Bundle();
            bundle.putInt(KEY_TACTICS, mTactics);
            bundle.putString(KEY_COMPETITIONID, mCompetitionId);
            goTargetActivity(MatchApplyListActivity.class, bundle);
        });
        mCompetitor.setLayoutManager(new LinearLayoutManager(getContext(), RecyclerView.HORIZONTAL, false));
        mCompetitor.setAdapter(mAdapter);
    }

    @Override
    protected void initView() {
    }

    @OnClick({R.id.tv_match_competitor_value, R.id.tv_match_create_event_notification_group_copy})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.tv_match_competitor_value:
                if (0 != mJoinNum) {
                    Bundle bundle = new Bundle();
                    bundle.putInt(KEY_TACTICS, mTactics);
                    bundle.putString(KEY_COMPETITIONID, mCompetitionId);
                    goTargetActivity(MatchApplyListActivity.class, bundle);
                }
                break;
            case R.id.tv_match_create_event_notification_group_copy:
                copy();
                break;
        }
    }

    private void copy() {
        ClipboardManager cm = (ClipboardManager) getActivity().getSystemService(Context.CLIPBOARD_SERVICE);
        ClipData mClipData = ClipData.newPlainText("Label", mEventNotification.getText().toString());
        cm.setPrimaryClip(mClipData);
    }

    /**
     * 提交报名
     */
    private void submit() {
        HashMap hashMap = new HashMap();
        hashMap.put(ApiConstant.KEY_TOKEN, HelperApplication.getToken());
        hashMap.put(KEY_COMPETITIONID, mCompetitionId);
        hashMap.put(KEY_TACTICS, mTactics);
        JSONObject data = new JSONObject(hashMap);
        LogUtil.log("FragmentMatchRecruitmentInformation submit data = " + data.toString());
        ApiResultCallback request = new ApiResultCallback() {

            @Override
            public void onSuccess(JsonObject data) {
                LogUtil.log("FragmentMatchRecruitmentInformation onSuccess data = " + data.toString());
                ToastUtil.showLong(R.string.match_create_registration_success);
                gotoMatchFragment();
            }

            @Override
            public void onFail(String msg) {
                LogUtil.log("FragmentMatchRecruitmentInformation onFail msg = " + msg);
                ToastUtil.showShort(msg);
            }

            @Override
            public void onError(String msg) {
                LogUtil.log("FragmentMatchRecruitmentInformation onError msg = " + msg);
                ToastUtil.showShort(msg);
            }
        };
        ProgressDialogCallback defaultProgressDialogCallback = new ProgressDialogCallback() {
            @Override
            public void showProgressDialog() {
                showLoading();
            }

            @Override
            public void dismissProgressDialog() {
                dismissLoading();
            }
        };
        ServerApi.post(ApiEnum.APP_CHECK_ISELIGIBLE_API.getUrl(), data, null, defaultProgressDialogCallback, d -> addDisposable(d), request);
    }

    /**
     * 跳转到赛事界面
     */
    private void gotoMatchFragment() {
        PMUtil.getInstance().finishAc(MatchMyActivity.class);
        PMUtil.getInstance().finishAc(MatchEnterActivity.class);
        getActivity().finish();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(RefreshEvent event) {
        if (event.clazzName.equals(getClass().getSimpleName())) {
            mAdapter.setNewInstance(null);
            fetchData();
        }
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EventBus.getDefault().register(this);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }
}
